import re
import requests
import logging
from time import sleep
from datetime import datetime
##cron: 31 9 * * *
##new Env("3SWG")

class ForumSigner:
    def __init__(self):
        # 基础配置
        self.notify_title = "3SWG论坛签到通知"
        self.sign_url = "https://www.3swg.com/plugin.php?id=dsu_paulsign:sign&operation=qiandao&infloat=1&sign_as=1&inajax=1"
        self.home_url = "https://www.3swg.com/forum.php"
        self.wechat_webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c4ed66c7-ea68-4b51-be3f-8319beb4504d"
        
        # 动态cookies配置
        self.cookies = {
            "STEm_2132_saltkey": "mNBCs7zM",
            "STEm_2132_lastvisit": str(int(datetime.now().timestamp()) - 3600),
            "STEm_2132_sid": "G0dC65",
            "STEm_2132_auth": "f5c56e1ujgg4ohjNO7PGeqFaG8JVUEGsNTaqPe%2BuoadsgiKPl93SV%2BSZrbZNuIm%2BP0pAdm1E5%2FZgprBlrykG12Ru",
            "STEm_2132_ulastactivity": "4936tDmgCoPyO%2FDn90Nre9WTfTJh5VD9eAUcCYV0xlr%2FQoP8GJq6",
            "STEm_2132_lip": f"59.39.223.211%2C{int(datetime.now().timestamp()) - 86400}",
            "STEm_2132_lastact": f"{int(datetime.now().timestamp())}%09plugin.php%09"
        }

        self.headers = {
            "Host": "www.3swg.com",
            "User-Agent": "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.6778.200 Mobile Safari/537.36",
            "Referer": self.home_url,
            "Content-Type": "application/x-www-form-urlencoded",
            "X-Requested-With": "XMLHttpRequest"
        }

        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s [%(levelname)s] %(message)s',
            handlers=[logging.StreamHandler()]
        )
        self.logger = logging.getLogger('3SWG')

    def _get_formhash(self):
        """获取最新的formhash值"""
        try:
            res = requests.get(self.home_url, headers=self.headers, cookies=self.cookies, timeout=10)
            if match := re.search(r'formhash=([a-f0-9]{8})', res.text):
                return match.group(1)
            return "eb4703e7"
        except Exception as e:
            self.logger.error(f"获取formhash失败: {e}")
            return "eb4703e7"

    def _parse_result(self, html):
        """解析签到结果"""
        try:
            if match := re.search(r'<div class="c">(.*?)</div>', html, re.DOTALL):
                text = re.sub(r'<[^>]+>', '', match.group(1))
                return ' '.join(text.split()).strip()
            return "响应解析失败"
        except Exception as e:
            self.logger.error(f"解析结果时出错: {e}")
            return "解析异常"

    def _send_wechat_notification(self, content):
        """发送企业微信机器人通知"""
        try:
            if not isinstance(content, str):
                content = str(content)
            
            payload = {
                "msgtype": "text",
                "text": {
                    "content": f"{self.notify_title}\n{content}",
                   # "mentioned_mobile_list": ["@all"]  # 如果需要@所有人
                }
            }
            
            response = requests.post(
                self.wechat_webhook,
                json=payload,
                timeout=10
            )
            
            if response.status_code == 200:
                self.logger.info("企业微信通知发送成功")
            else:
                self.logger.error(f"企业微信通知发送失败: {response.text}")
        except Exception as e:
            self.logger.error(f"发送企业微信通知时出错: {e}")

    def run(self):
        """执行签到流程"""
        form_data = {
            "formhash": self._get_formhash(),
            "qdxq": "kx",
            "qdmode": "2",
            "todaysay": "",
            "fastreply": "0"
        }

        try:
            self.logger.info("正在执行3SWG论坛签到...")
            
            response = requests.post(
                self.sign_url,
                headers=self.headers,
                cookies=self.cookies,
                data=form_data,
                timeout=15
            )
            response.raise_for_status()

            result = self._parse_result(response.text)
            if "已经签到" in result:
                msg = "⚠️ 今日已签到，请勿重复操作"
                self.logger.warning(msg)
                self._send_wechat_notification(msg)
            elif "恭喜" in result:
                if reward := re.search(r'金钱\s*(\d+)', result):
                    msg = f"🎉 签到成功！获得 {reward.group(1)} 金钱"
                else:
                    msg = f"🎉 签到成功！{result}"
                self.logger.info(msg)
                self._send_wechat_notification(msg)
            else:
                msg = f"❓ 未知响应: {result}"
                self.logger.warning(msg)
                self._send_wechat_notification(msg)

        except requests.exceptions.RequestException as e:
            error_msg = f"❌ 网络请求失败: {str(e)}"
            self.logger.error(error_msg)
            self._send_wechat_notification(error_msg)
        except Exception as e:
            error_msg = f"❌ 程序异常: {str(e)}"
            self.logger.error(error_msg)
            self._send_wechat_notification(error_msg)

if __name__ == "__main__":
    bot = ForumSigner()
    bot.run()